import random

from Autotests.Suites.StressTest.Operations.CommonOperations import CommonOperations
from Autotests.Suites.StressTest.Operations.PartnerOperations import PartnerOperations
from Autotests.Suites.StressTest.Operations.UserOperations import UserOperations
from Autotests.Suites.StressTest.Selector.GroupSelector import GroupSelector
from Autotests.Suites.StressTest.Statistics import Statistics


class PartnersSelector:

    def runForAllPartners(self, manserv):
        statistics = Statistics()
        subpartners = manserv.EnumeratePartners(parentPartnerId = 1,
                                                fetchRecursively = random.choice([True, True, False, False, False]))
        while True:
            statistics.beginMethod()
            partner = random.choice(subpartners.partnerInfo)
            partnerId = partner.id
            GroupSelector().selectScenario(manserv, partnerId)
            statistics.endMethod()


    def runForSimplePartner(self, manserv):
        statistics = Statistics()
        partnerId = self._getStressTestPartner(manserv)

        if partnerId:
            while True:
                statistics.beginMethod()
                subPartnerId = self._getSubpartner(manserv, partnerId)
                GroupSelector().selectScenario(manserv, subPartnerId)
                statistics.endMethod()
        else:
            print 'simple partner, run scenario error'


    def _getSubpartner(self, manserv, partnerId):
        try:
            subpartners = manserv.EnumeratePartners(parentPartnerId = partnerId, fetchRecursively = True)
            if subpartners:
                if len(subpartners.partnerInfo) > 3:
                    rand = random.randint(0, len(subpartners.partnerInfo) - 1)
                    return subpartners.partnerInfo[rand].id
        except:
            pass
        return partnerId


    def _getStressTestPartner(self, manserv):
        partnerId = None
        subpartners = manserv.EnumeratePartners(parentPartnerId = 1, fetchRecursively = False)
        for partner in subpartners.partnerInfo:
            if partner.name == 'StressTestPartner':
                partnerId = partner.id

        if not partnerId:
            partnerId = PartnerOperations()._addStressTestPartner(manserv)

        try:
            UserOperations()._addStressTestUser(manserv, partnerId)
        except:
            pass

        CommonOperations()._loginStressTestUser(manserv, partnerId)

        return partnerId
